﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VirtualTournaments.Business.Tournaments
{
	public class MatchWithPenalties : MatchWithWinner
	{
		private const byte NUMBER_PENALTIES = 5;
		private const double PENALTY_GOAL_PROBABILITY = 0.7;

		public MatchWithPenalties(Tournament tournament, Team Local, Team Visitor) : base(tournament, Local, Visitor) { }

		protected override void BreakTie()
		{
			byte localPenaltyGoals = 0;
			byte visitorPenaltyGoals = 0;
			byte localPenaltiesLeft = NUMBER_PENALTIES;
			byte visitorPenaltiesLeft = NUMBER_PENALTIES;

			for (int i = (localPenaltiesLeft + visitorPenaltiesLeft);
				(localPenaltyGoals + localPenaltiesLeft >= visitorPenaltyGoals) && (visitorPenaltyGoals + visitorPenaltiesLeft >= localPenaltyGoals) && (i > 0);
				i--)
			{
				if (i % 2 == 0)
				{
					if (RANDOM.NextDouble() < PENALTY_GOAL_PROBABILITY)
						localPenaltyGoals++;
					localPenaltiesLeft--;
				}
				else
				{
					if (RANDOM.NextDouble() < PENALTY_GOAL_PROBABILITY)
						visitorPenaltyGoals++;
					visitorPenaltiesLeft--;
				}
			}
			while (localPenaltyGoals == visitorPenaltyGoals)
			{
				if (RANDOM.NextDouble() < PENALTY_GOAL_PROBABILITY)
					localPenaltyGoals++;
				if (RANDOM.NextDouble() < PENALTY_GOAL_PROBABILITY)
					visitorPenaltyGoals++;
			}
			Result = new MatchWithPenaltiesResult(Result, localPenaltyGoals, visitorPenaltyGoals);
		}

	}
}
